import 'dart:io';
import 'dart:ui';

import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_syt/theme/theme_color.dart';
import 'package:flutter_syt/utils/utils_dlog.dart';
import 'package:flutter_syt/utils/utils_other.dart';
import 'package:flutter_syt/widgets/common_button.dart';
import 'package:intl/intl.dart';
import 'package:flutter_syt/api/api.dart';
import 'package:flutter_syt/application.dart';
import 'package:flutter_syt/domain/login/widgets/login_account_form.dart';
import 'package:flutter_syt/generated/l10n.dart';
import 'package:flutter_syt/global_common.dart';
import 'package:flutter_syt/global_easy_loading.dart';
import 'package:flutter_syt/routes.all.dart';
import 'package:flutter_syt/utils/click_utils.dart';
import 'package:yyy_route_annotation/yyy_route_annotation.dart';

import '/domain/login/widgets/login_protocol.dart';
import 'widgets/login_container.dart';
import 'widgets/login_input_decorator.dart';

@RoutePage(name: "loginByPwd")
class LoginByPasswordPage extends StatefulWidget {
  const LoginByPasswordPage();

  @override
  _LoginByPasswordPageState createState() => _LoginByPasswordPageState();
}

class _LoginByPasswordPageState extends State<LoginByPasswordPage> {
  // late TabController _tabController;
  final _formKey = GlobalKey<FormState>();

  FocusNode phoneFocusNode = FocusNode();
  FocusNode pwdFocusNode = FocusNode();

  // late PhoneWithAreaCodeEntity _phone;
  String? _password;
  String? _account;
  bool _agree = false;

  bool blurBackground = false;

  // FocusNode phoneFocusNode = FocusNode();
  // FocusNode pwdFocusNode = FocusNode();

  // late PhoneWithAreaCodeEntity _phone;
  // late String _password;
  bool pwsPhoneobscureText = true;

  // bool _agree = false;

  Future _login() async {
    // await API.shared.login
    //     .phoneSecretLogin(_phone.areaCode, _phone.phone, _password);
    // DLog(_phone);
    // try {

    await API.shared.login.accountLogin(
        _account ?? '',
        _password ?? '',
        (Platform.isIOS
            ? appContext.iOSInfo.identifierForVendor
            : appContext.andriodInfo.androidId));
    await API.shared.user.updateUserInfo('lang',
        appContext.storage.getString("storyLocal") ?? Intl.getCurrentLocale());
    // } catch (e) {
    //   UtilsOther.showCustomShowError(e);
    // }

    // if (me.serial_number > 0) {
    //   API.shared.common.indexSetting().then((IndexSetting setting) {
    //     ProviderIndexSetting indexSettingProvider =
    //         Provider.of<ProviderIndexSetting>(appContext.context!,
    //             listen: false);
    //     indexSettingProvider.indexSetting = setting;
    //   });
    // }
  }

  Future _submit() async {
    if (!_agree) {
      customShowToast(S.of(context).privacy_policy_consent_t);
      return;
    }
    final form = _formKey.currentState;
    if (form!.validate()) {
      form.save();
      try {
        await _login();
        customShowToast(S.of(context).login_success);
        try {
          GlobalData.bindPush();
          GlobalData.getIndexSetting();
        } catch (e) {}
        if (GlobalData.pageFrom.isEmpty) {
          Navigator.of(context).pop();
        } else {
          Navigator.of(context).popUntil((route) {
            var name = route.settings.name;
            if (name != null) {
              return name.startsWith(GlobalData.pageFrom);
            }
            return route.isFirst;
          });
        }
      } catch (e) {
        DLog(e);
        UtilsOther.showCustomShowError(e);
      }
    }
  }

  @override
  void initState() {
    super.initState();
    // _tabController = TabController(length: 2, vsync: this);
    // phoneFocusNode.addListener(() {
    //   setState(() {
    //     blurBackground = phoneFocusNode.hasFocus;
    //   });
    // });
    // pwdFocusNode.addListener(() {
    //   setState(() {
    //     blurBackground = pwdFocusNode.hasFocus;
    //   });
    // });
  }

  // Future _login() async {
  //   await API.shared.login
  //       .phoneSecretLogin(_phone.areaCode, _phone.phone, _password);
  //   appContext.storage.getString("storyLocal");
  //   await API.shared.user.updateUserInfo('lang',
  //       appContext.storage.getString("storyLocal") ?? Intl.getCurrentLocale());
  // }

  // Future _submit() async {
  //   if (!_agree) {
  //     customShowToast(S.of(context).privacy_policy_consent_t);
  //     return;
  //   }
  //   final form = _formKey.currentState;
  //   if (form!.validate()) {
  //     form.save();
  //     await loading(_login, text: S.of(context).on_login);
  //     customShowToast(S.of(context).login_success);
  //     try {
  //       GlobalData.bindPush();
  // GlobalDat.getIndexSetting();
  //     } catch (e) {}
  //     if (GlobalData.pageFrom.isEmpty) {
  //       Navigator.of(context).pop();
  //     } else {
  //       Navigator.of(context).popUntil((route) {
  //         var name = route.settings.name;
  //         if (name != null) {
  //           return name.startsWith(GlobalData.pageFrom);
  //         }
  //         return route.isFirst;
  //       });
  //     }
  //   }
  // }

  @override
  void dispose() {
    // phoneFocusNode.dispose();
    // pwdFocusNode.dispose();
    // _tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // 避免键盘弹起时高度错误
      resizeToAvoidBottomInset: false,
      body: GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: ClickUtils.debounce(() {
          // 触摸收起键盘
          FocusScope.of(context).requestFocus(FocusNode());
        }),
        child: LoginContainer(
          // blurBackground: blurBackground,
          child: Form(
            key: _formKey,
            child: Container(
              padding: EdgeInsets.symmetric(vertical: 0, horizontal: 30),
              child: Column(
                children: [
                  Container(
                    alignment: Alignment.centerLeft,
                    margin: EdgeInsets.only(bottom: 20.w),
                    child: Text(
                      S().login_accountpws,
                      style: TextStyle(
                          color: Colors.black87,
                          fontSize: 20,
                          fontWeight: FontWeight.w600),
                    ),
                  ),

                  //       BlurRectWidget(
                  //   TextFormField(
                  //     enableInteractiveSelection: true,
                  //     maxLength: 32,
                  //     autofocus: false,
                  //     controller: _textEditingController,
                  //     focusNode: phoneFocusNode,
                  //     style: TextStyle(
                  //       color: Colors.white,
                  //       fontSize: 16,
                  //       height: 1.5,
                  //       fontWeight: FontWeight.bold,
                  //     ),
                  //     cursorColor: Colors.white,
                  //     decoration: LoginInputDecoration(
                  //         hintText: S.of(context).enter_mobile_email),
                  //     onSaved: (val) {
                  //       if (val != null) {
                  //         _email = val;
                  //         appContext.storage.setString("login_email", _email);
                  //       }
                  //     },
                  //     keyboardType: TextInputType.text,
                  //     autocorrect: false,
                  //   ),
                  // ),
                  // BlurRectWidget(
                    LoginAccountForm(
                      focusNode: phoneFocusNode,
                      hintText: S.of(context).login_inputAccount,
                      onSaved: (newValue) {
                        _account = newValue;
                      },
                    ),
                    // padding: 0,
                  // ),
                  // BlurRectWidget(
                  //   LoginPhoneFormField(
                  //     focusNode: phoneFocusNode,
                  //     onSaved: (val) {
                  //       _phone = val!;
                  //     },
                  //   ),
                  //   padding: 0,
                  // ),
                 const SizedBox(height: 24),
                  // BlurRectWidget(
                  TextFormField(
                    enableInteractiveSelection: false,
                    maxLength: 16,
                    inputFormatters: [
                      FilteringTextInputFormatter.deny(appContext.emojiRegexp)
                    ],
                    keyboardType: TextInputType.visiblePassword,
                    autofocus: false,
                    focusNode: pwdFocusNode,
                    style: const TextStyle(
                      color: ThemeColor.colorTextB1,
                      fontSize: 14,
                      // height: 1.5,
                      fontWeight: FontWeight.w400,
                    ),

                    cursorColor: ThemeColor.primaryColor,
                    decoration: LoginInputDecoration(
                        suffixIcon: GestureDetector(
                          onTap: ClickUtils.debounce(() {
                            if (mounted) {
                              setState(() {
                                pwsPhoneobscureText = !pwsPhoneobscureText;
                              });
                            }
                          }),
                          child: Container(
                              width: 20,
                              child: Center(
                                child: Image.asset(
                                  pwsPhoneobscureText
                                      ? 'assets/images/comment_obscureText_open.png'
                                      : 'assets/images/comment_obscureText_close.png',
                                  width: 20,
                                  color: Colors.black87,
                                  height: pwsPhoneobscureText ? 20 : 14,
                                ),
                              )),
                        ),
                        hintText: S.of(context).enter_password),
                    validator: (val) {
                      if (val != null) {
                        if (val.length < 8 || val.length > 16) {
                          customShowToast(S.of(context).Password_8_16);
                          return '';
                        }
                      }
                      return null;
                    },
                    onSaved: (val) => _password = val!,
                    obscureText: pwsPhoneobscureText,

                    // keyboardType: TextInputType.number,
                    autocorrect: false,
                  ),
                  // padding: 0),
                  Container(
                    margin: EdgeInsets.only(top: 14.w),
                    width: double.infinity,
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Container(
                          // margin: ,
                          constraints: BoxConstraints(maxWidth: 200.w),
                          child: GestureDetector(
                            onTap: ClickUtils.debounce(() {
                              RouteManager.push(
                                context,
                                RoutMapping.loginByCode(),
                              );
                            }),
                            child: Text(
                              S.of(context).log_in_with_code,
                              style: TextStyle(
                                fontSize: 14,
                                color: Colors.black87,
                              ),
                            ),
                          ),
                        ),
                        GestureDetector(
                          onTap: ClickUtils.debounce(() {
                            // customShowToast(S().standy_by);
                            RouteManager.push(
                              context,
                              RoutMapping.forgetPasswordPage(0),
                            );
                          }),
                          child: Text(
                            S.of(context).Forgot_password,
                            style: TextStyle(
                              fontSize: 14,
                              color: Colors.black87,
                            ),
                          ),
                        )
                      ],
                    ),
                  ),
                  SizedBox(
                    height: 20,
                  ),
                  LoginProtocol(onChange: (value) {
                    setState(() {
                      _agree = value;
                    });
                  }),
                  Container(
                    margin: const EdgeInsets.only(top: 30, bottom: 16),
                    width: double.infinity,
                    // child: ElevatedButton(
                    //     child: Text(
                    //       S.of(context).log_in,
                    //       style: TextStyle(fontWeight: FontWeight.bold),
                    //     ),
                    //     onPressed: ClickUtils.debounce(
                    //       () {
                    //         _submit();
                    //       },
                    //     )),

                    child: CommonButton.expend(
                      title: S.of(context).log_in,
                      // height: 30,
                      onAsyncClick: () async {
                        await _submit();
                        // await Future.delayed(Duration(seconds: 2));
                      },
                    ),
                  ),
                  RichText(
                      text: TextSpan(
                          style: TextStyle(fontSize: 14, color: Colors.black87),
                          children: [
                        TextSpan(
                          text: S().login_infoLeft,
                        ),
                        TextSpan(
                          text: S().login_infoTap,
                          recognizer: TapGestureRecognizer()
                            ..onTap = () {
                              RouteManager.push(
                                context,
                                RoutMapping.register(),
                              );
                            },
                          style: const TextStyle(
                              fontSize: 14,
                              color: ThemeColor.primaryColor,
                              fontWeight: FontWeight.bold,
                              decorationColor: ThemeColor.primaryColor,
                              decorationThickness: 2,
                              // decorationStyle: TextDecorationStyle.double,
                              decoration: TextDecoration.underline),
                        ),
                        TextSpan(
                          text: S().login_infoRight,
                          style: TextStyle(fontSize: 14),
                        ),
                      ])),
                  SizedBox(
                    height: 10.w,
                  )
                  // Container(
                  //   // margin: EdgeInsets.only(top: 100),
                  //   child: TextButton(
                  //     style: TextButton.styleFrom(
                  //       primary: Colors.white,
                  //     ),
                  //     onPressed: ClickUtils.debounce(
                  //       () {
                  //         RouteManager.push(
                  //           context,
                  //           RoutMapping.register(),
                  //         );
                  //       },
                  //     ),
                  //     child: Text(
                  //       S.of(context).sign_up,
                  //       style: TextStyle(fontWeight: FontWeight.bold),
                  //     ),
                  //   ),
                  // ),
                ],
              ),
            ),
          ),
          // child: Column(
          //   mainAxisSize: MainAxisSize.min,
          //   children: [

          // Container(
          //   padding: EdgeInsets.symmetric(vertical: 0, horizontal: 15),
          //   height: 52,
          //   child: NormalTabs(
          //     [
          //       ScrollerTabEntity.create(
          //           'type', S.current.login_phone, 0, ''),
          //       ScrollerTabEntity.create(
          //           'type', S.current.login_email, 0, ''),
          //     ],
          //     _tabController,
          //     textColor: Colors.white,
          //     alignment: Alignment.centerLeft,
          //   ),
          // ),
          // Container(
          //   // color: Colors.black.withOpacity(0.1),
          //   height: 12,
          // ),
          // SizedBox(
          //   height: 500,
          //   child: TabBarView(
          //     controller: _tabController,
          //     children: [LoginPasswordPhone(), LoginPasswordEmail()],
          //   ),
          // ),
          // ],
          // ),
        ),
        // ),
      ),
    );
  }
}

class BlurRectWidget extends StatelessWidget {
  final Widget _widget;
  double _padding = 0;

  BlurRectWidget(this._widget, {double padding = 0}) {
    if (padding != 0) this._padding = padding;
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: ClipRRect(
        borderRadius: BorderRadius.all(Radius.circular(8)),
        child: BackdropFilter(
          filter: ImageFilter.blur(
            sigmaX: 20,
            sigmaY: 20,
          ),
          child: Container(
            color: Colors.white24,
            padding: EdgeInsets.all(_padding),
            child: _widget,
          ),
        ),
      ),
    );
  }
}
